package com.zhuimeng.ossdemo.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.zhuimeng.ossdemo.conf.AliyunConfig;
import com.zhuimeng.ossdemo.entry.UploadResult;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Service
public class FileUploadService {
    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private OSSClient ossClient;
    private static final String[] IMAGE_TYPE = new String[]{".bmg",
        ".jpg",".jpeg",".gif",".png"};
    public UploadResult upload(MultipartFile uploadFile){
        boolean isLegal = false;
        String filename = uploadFile.getOriginalFilename();
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(filename,type)){
                isLegal = true;
                break;
            }
        }
        UploadResult uploadResult = new UploadResult();
        if (!isLegal){
            uploadResult.setStatus("error");
            return uploadResult;
        }
        String filePath = getFilePath(filename);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(),filename,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            uploadResult.setStatus("error");
            return uploadResult;
        }
        uploadResult.setStatus("done");
        uploadResult.setName(this.aliyunConfig.getUrlPrefix() + filename);
        uploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return uploadResult;
    }


    public void down(OutputStream os, String fileName) throws IOException {
        OSSObject object = ossClient.getObject(aliyunConfig.getBucketName(), fileName);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(object.getObjectContent());
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);
        byte[] bytes = new byte[1024];
        int lenght = 0;
        while ((lenght=bufferedInputStream.read(bytes))!=-1){
            bufferedOutputStream.write(bytes,0,lenght);
        }
        if (bufferedOutputStream != null){
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        }
        if (bufferedInputStream != null){
            bufferedInputStream.close();
        }
    }

    public UploadResult delete(String objName){
        ossClient.deleteObject(aliyunConfig.getBucketName(),objName);
        UploadResult uploadResult = new UploadResult();
        uploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        uploadResult.setName(objName);
        uploadResult.setStatus("done");
        uploadResult.setResponse("success");
        return uploadResult;
    }

    private String getFilePath(String sourceFileName){
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() + "." + StringUtils.substringAfterLast(sourceFileName, ".");
    }
}
